﻿using AutoMapper;
using MediatR;
using WeatherHistory.Data.Repositories.Interfaces;
using WeatherHistory.Shared.Exceptions;
using WeatherHistory.Shared.Helpers;

namespace WeatherHistory.Api.CommandsQueries.Commands.Accounts.Authentication;

public class AuthenticationAccountsCommandHandler : IRequestHandler<AuthenticationAccountsCommandRequest, AuthenticationAccountsCommandResponse>
{
    private readonly IAccountRepository _accountRepository;
    private readonly IMapper _mapper;

    public AuthenticationAccountsCommandHandler(IMapper mapper, IAccountRepository accountRepository)
    {
        _mapper = mapper;
        _accountRepository = accountRepository;
    }

    public async Task<AuthenticationAccountsCommandResponse> Handle(AuthenticationAccountsCommandRequest request, CancellationToken cancellationToken)
    {
        var account = await _accountRepository
            .FirstOrDefaultAsync(x => x.Email == request.Email.ToLower()
                                      && x.PasswordHash == SecurityHelper.ComputeSha256Hash(request.Password), cancellationToken);
        var pass = SecurityHelper.ComputeSha256Hash(request.Password);
        if (account == null) throw new UnauthorizedException("Неверная почта или пароль");

        return _mapper.Map<AuthenticationAccountsCommandResponse>(account);
    }
}